Skip to content

fix(mcp): pool startup resilience & spawn-cycle protection - #2

Merged
SWSAmor merged 4 commits into
mainfrom
fix/mcp-pool-startup-resilience
Jun 1, 2026
Merged

SWSAmor merged 4 commits into
mainfrom
fix/mcp-pool-startup-resilience

Conversation

@SWSAmor

@SWSAmor SWSAmor commented Jun 1, 2026

Copy link
Copy Markdown
Owner

Summary

Hardens code-executor startup against two production failure modes seen when running behind an MCP host (the Hermes agent gateway):

  1. Respawn storm — the upstream MCP handshake was answered only after connecting to every downstream server, so one slow/unreachable server delayed startup past the host's timeout → the host killed & respawned repeatedly, leaking child MCP processes each time.
  2. Fork bomb — a cyclic MCP topology: the host lists code-executor as a server, and code-executor's config lists that same host (hermes mcp serve) as a downstream server, so the two spawn each other indefinitely. (Not direct self-inclusion — that is correctly excluded by name.)

Full diagnosis and design rationale: docs/mcp-pool-startup-resilience.md.

What changed

  • Decoupled startup (src/index.ts): connect the upstream stdio transport first, initialize the downstream pool in the background (poolReady); tool handlers await readiness. Total downstream failure no longer crashes the server.
  • Per-server connect timeout (POOL_CONNECT_TIMEOUT_MS, default 15 s): a hung server is marked failed instead of blocking the pool; its child is killed by PID on timeout (AbortController kill is unreliable on Bun).
  • Parent-PID ancestry guard: if any ancestor process is itself a code-executor, run in LEAF MODE (connect to nothing). Reliable even when the host strips the child environment — which hermes mcp serve does, so the earlier env-marker approach failed live. Override: CODE_EXECUTOR_ALLOW_NESTED=1.
  • Path-based self-exclusion: skip a downstream whose command IS code-executor itself (binary basename / process.execPath), regardless of config key name.
  • Orphan reaping: track in-flight transports + synchronous process.on('exit') SIGKILL backstop.
  • Per-server startup status report: one ✓/✗ line per server with duration & reason.

Tests

  • tests/recursion-guard.test.ts (new): self-exclusion, leaf-mode guard, CODE_EXECUTOR_ALLOW_NESTED override.
  • tests/pool-config-validation.test.ts: connectTimeoutMs default + parsing.
  • Affected suites green; full suite: 678 passed, 60 pre-existing env-only failures (systemd on macOS, deno sandbox, network) — zero regression.
  • Process-spawning behaviors (background init, timeout-kills-child, orphan reaping, real ps ancestry) verified manually on the bun --compile binary; see the docs note's Verification section.

Notes

  • Ships as a bun --compile binary; bin/code-executor-mcp is gitignored, rebuild with npm run build:binary.
  • "Exactly one process" for the cyclic config requires breaking the config cycle (remove the host entry from code-executor's downstream config); the guards make the topology safe (stable: 1 full + 1 leaf), not invisible.

🤖 Generated with Claude Code

SWSAmor and others added 4 commits May 31, 2026 22:10
Hermes (and any MCP host) restarted code-executor in a tight loop because
the upstream stdio handshake was answered only AFTER connecting to every
downstream server. A single slow/unreachable server (notably HTTP ones)
blocked startup past the host timeout, so the host killed and respawned the
process repeatedly — each spawn leaking ~15 child MCP processes.

Root cause + amplifiers fixed:

1. Background pool init (index.ts): connect the upstream stdio transport
   FIRST, then initialize the downstream pool in the background. The host
   handshake now returns instantly regardless of downstream health. Tool
   handlers await `poolReady` before executing (bounded by per-server
   timeouts). Total downstream failure no longer crashes the server.

2. Per-server connect timeout (client-pool.ts): each connect races against
   POOL_CONNECT_TIMEOUT_MS (default 15s, Zod-validated). A hung server is
   marked failed instead of blocking the pool. On timeout the spawned child
   is killed explicitly by PID (SIGKILL) in addition to transport.close(),
   since AbortController-based kill is unreliable under the Bun runtime.

3. Process-leak hardening (client-pool.ts, index.ts): track in-flight
   transports in `pendingStdioTransports` so children spawned during a
   mid-init teardown are still reaped; add a synchronous `process.on('exit')`
   backstop (killChildrenSync) that SIGKILLs all spawned children even on a
   hard exit.

Partial availability: a failed/timed-out server is never added to
clients/toolCache, so its tools are neither discoverable nor callable — the
remaining servers stay fully available and startup continues without it.

Startup status report: initialize() now logs one line per configured server
(✓/✗ with duration and failure reason) plus an N/M summary, so it is always
clear which servers came up and which did not.

Verified on the bun --compile binary: transport connects before pool init,
per-server timeout fires and kills the hung child, no orphans remain after
shutdown, and the server keeps running when all downstream servers fail.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Live diagnosis: the fork bomb was NOT direct self-inclusion (code-executor is
correctly excluded from its own pool by name). It was a CYCLIC MCP topology —
the host (an agent gateway) lists code-executor as a server, and code-executor's
config lists that same host (its `mcp serve`) as a downstream server. The two
spawn each other indefinitely (code-executor → host → code-executor → ...),
producing dozens of processes per minute. Name-based self-exclusion can't catch
this: the intermediary is a different program.

Guard: at startup, walk the parent-PID chain; if any ancestor process is itself
a code-executor (argv0 basename = code-executor-mcp), run in LEAF MODE — connect
to no downstream servers and return immediately, terminating the cycle.

Design notes:
- PID ancestry, not an inherited env marker: the observed intermediary
  (`hermes mcp serve`) does NOT forward our environment to the code-executor it
  spawns, so a marker never arrives. Parent PIDs are always readable.
- The whole chain, not just the direct parent: in the cyclic case the direct
  parent is the host, and the code-executor ancestor is one hop further up.
- argv0 basename match, not the full command line: avoids a false positive
  where a shell wrapper (`sh -c "... /path/code-executor-mcp ..."`) is mistaken
  for a code-executor — which wrongly put a top-level instance into leaf mode.
- Escape hatch: CODE_EXECUTOR_ALLOW_NESTED=1 disables the guard.
- Best-effort: if `ps` is unavailable (e.g. Windows) the guard does not engage.

Verified on the bun --compile binary, simulating a host that strips the
environment: the top-level instance runs full and connects downstream, while the
instance it transitively spawns detects the code-executor ancestor, logs LEAF
MODE, and spawns nothing — bounding the chain.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…stream)

Complements the name-based self-exclusion (which only matches the conventional
"code-executor" config key) and the ancestry guard. At pool init, any downstream
STDIO server whose command is code-executor itself — basename "code-executor-mcp"
or an exact match of process.execPath — is skipped regardless of its config key
name, with a logged reason. This catches "wired self in under a different name",
the original suspected cause.

Note: this does NOT remove a downstream that loops back indirectly through a
different host program (e.g. an agent gateway), because that command is not the
code-executor binary; the parent-PID ancestry guard handles that case, and
breaking the config cycle is the way to drop the (harmless, leaf-mode) extra
process entirely.

Verified on the bun --compile binary: code-executor configured as a downstream
under a non-"code-executor" key is skipped at startup.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…ilience

- tests/recursion-guard.test.ts: path-based self-exclusion (self wired under any
  key name, and exact process.execPath match) and the parent-PID ancestry leaf
  guard, including the CODE_EXECUTOR_ALLOW_NESTED override.
- tests/pool-config-validation.test.ts: connectTimeoutMs default (15000) and
  POOL_CONNECT_TIMEOUT_MS parsing.
- CHANGELOG.md: [Unreleased] entry summarizing the startup-resilience and
  spawn-cycle fixes.
- docs/mcp-pool-startup-resilience.md: full diagnosis, fixes, and the rationale
  for each design decision (incl. why ancestry beats an env marker, why argv0
  matching, why leaf mode not exit).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@SWSAmor
SWSAmor merged commit afd5c8c into main Jun 1, 2026
0 of 2 checks passed
@SWSAmor
SWSAmor deleted the fix/mcp-pool-startup-resilience branch June 1, 2026 08:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant